package com.example.demo.service.impl;

import com.example.demo.dao.PropMapper;
import com.example.demo.entity.DTO.UpdatePropDTO;
import com.example.demo.entity.PO.PetPO;
import com.example.demo.entity.PO.PropPO;
import com.example.demo.entity.VO.pet.PetVO;
import com.example.demo.entity.VO.pet.PropVO;
import com.example.demo.enums.PropTypeEnum;
import com.example.demo.service.PetService;
import com.example.demo.service.PropService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PropServiceImpl implements PropService {

    private final PropMapper propMapper;


    @Autowired
    public PropServiceImpl(PropMapper propMapper) {
        this.propMapper = propMapper;
    }


    @Override
    public List<PropVO> getPropsByUserId(Integer userId, String type) {
        PropTypeEnum typeEnum = PropTypeEnum.getTypeByValue(type);

        List<PropPO> propPOList = propMapper.getPropsByUserId(userId, typeEnum == null ? null : typeEnum.getId());
        List<PropVO> propVOList = propPOList.stream().map(propPO -> PropVO.builder()
                        .propId(propPO.getPropId())
                        .amount(propPO.getAmount())
                        .name(propPO.getName())
                        .type(typeEnum)
                        .build())
                .collect(Collectors.toList());

        return propVOList;
    }


    /**
     * 暂时弃用
     * @param userId 用户id
     * @param propId 道具id
     * @param updateAmount 更新数量,正数为增加，负数为减少
     */
    @Override
    public void updatePropAmount(Integer userId, Integer propId, Integer updateAmount) {



        propMapper.updatePropAmount(userId, propId, updateAmount, System.currentTimeMillis());
    }

    @Override
    public void updatePropAmount(List<UpdatePropDTO> updatePropDTOList, Integer userId) {
        updatePropDTOList.forEach(updatePropDTO -> {
            PropPO existing = propMapper.getPropByPropId(userId, updatePropDTO.getPropId());

            if (existing == null) {
                propMapper.saveProp(PropPO.builder()
                        .userId(userId)
                        .propId(updatePropDTO.getPropId())
                        .type(PropTypeEnum.getTypeByValue(updatePropDTO.getType()))
                                .name(updatePropDTO.getName())
                        .amount(0)
                        .createdAt(System.currentTimeMillis())
                        .updatedAt(System.currentTimeMillis())
                        .build());
                return;
            }

            propMapper.updatePropAmount(userId, updatePropDTO.getPropId(), updatePropDTO.getUpdateAmount(), System.currentTimeMillis());
        });
    }
}
